require 'digest/sha1'

class User < ActiveRecord::Base
  validates_presence_of :first_name
  validates_presence_of :last_name
  validates_presence_of :role_id
  validates_presence_of :name
  validates_uniqueness_of :name
  
  attr_accessor :password_confirmation 
  validates_confirmation_of :password
  
  belongs_to  :role
  
  def validate
    errors.add_to_base("Password missing!") if password_hash.blank?
  end
  
  def create_new_salt
    self.password_salt = self.object_id.to_s + rand.to_s
  end
  
  def self.encrypted_password(password, salt)
    string_to_hash = password + "calsssichomessale" + salt
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    return if @password.blank?
    create_new_salt
    self.password_hash = User.encrypted_password(self.password, self.password_salt)
  end
  
  def self.authenticate(name, pwd)
    user = self.find_by_name(name)
    if user
      expected_password = User.encrypted_password(pwd, user.password_salt)
      if(expected_password != user.password_hash)
        user = nil
      end
    end
    user
  end
  
 def name
   first_name + ' ' + last_name
 end
end
